package com.archive.forum.service;

import com.archive.forum.dto.GithubUser;
import com.archive.forum.exception.CustomizeException;
import com.archive.forum.exception.ExceptionEnum;
import com.archive.forum.mapper.UserMapper;
import com.archive.forum.model.User;
import com.archive.forum.model.UserExample;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.List;
import java.util.Objects;
import java.util.UUID;

@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;
    //github登录创建或更新用户信息
    public String githubLogin(GithubUser githubUser, HttpServletResponse response,User accountuser,Model model) {
        UserExample userExample = new UserExample();
        userExample.createCriteria().andGithubIdEqualTo(githubUser.getId());
        List<User> users = userMapper.selectByExample(userExample);
        // 情况1：用户已登录（绑定GitHub账号）
        if (accountuser != null && accountuser.getId() != null) {
            if (users.isEmpty()) {
                // 绑定GitHub账号到当前用户
                User updateUser = new User();
                updateUser.setId(accountuser.getId());
                updateUser.setGithubId(githubUser.getId());
                userMapper.updateByPrimaryKeySelective(updateUser);
                model.addAttribute("success", "GitHub账号绑定成功");
            } else {
                // GitHub账号已被其他用户绑定
                model.addAttribute("error", "该GitHub账号已被其他用户绑定");
            }
            model.addAttribute("user", accountuser);
            model.addAttribute("section", "account");
            model.addAttribute("sectionName", "我的账户");
            return "user";
        }

        // 情况2：新用户通过GitHub注册
        if (users.isEmpty()) {
            User newUser = new User();
            String token = UUID.randomUUID().toString();
            newUser.setToken(token);
            newUser.setAccountId(new SecureRandom().nextInt(2100000000));
            newUser.setNickname(githubUser.getName());
            newUser.setBio(githubUser.getBio());
            newUser.setGithubId(githubUser.getId());
            newUser.setGmtCreate(System.currentTimeMillis());
            newUser.setGmtModified(newUser.getGmtCreate());
            newUser.setAvatarUrl(githubUser.getAvatarUrl());
            userMapper.insertSelective(newUser);
            response.addCookie(new Cookie("token", token));
        }
        // 情况3：已有用户通过GitHub登录
        else {
            User existingUser = users.get(0);
            User updateUser = new User();
            updateUser.setGmtModified(System.currentTimeMillis());
            UserExample example = new UserExample();
            example.createCriteria().andIdEqualTo(existingUser.getId());
            userMapper.updateByExampleSelective(updateUser, example);
            response.addCookie(new Cookie("token", existingUser.getToken()));
        }

        return "redirect:/";
    }
    //根据唯一名查询用户信息
    public boolean isExist(String name) {
        UserExample userExample = new UserExample();
        userExample.createCriteria().andNameEqualTo(name);
        List<User> users = userMapper.selectByExample(userExample);
        return !users.isEmpty();
    }
    //注册
    public void register(User user,HttpServletResponse response) {
        if(user !=null){
            String token = UUID.randomUUID().toString();
            user.setToken(token);
            //十位随机数id在这系统上理论上不会重复，懒得加验证了

            user.setAccountId(new SecureRandom().nextInt(2100000000));
            user.setGmtCreate(System.currentTimeMillis());
            user.setGmtModified(user.getGmtCreate());
            userMapper.insertSelective(user);
            response.addCookie(new Cookie("token", token));
        }
    }
    //sha1加密密码
    public String sha1(String password) {
        try {
            MessageDigest md = MessageDigest.getInstance("SHA-1");
            byte[] bytes = md.digest(password.getBytes());
            StringBuilder sb = new StringBuilder();
            for (byte b : bytes) {
                sb.append(String.format("%02x", b));
            }
            return sb.toString();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }
    //登录
    public String login(User user, HttpServletResponse response, Model model){
        if(user !=null){
            UserExample userExample = new UserExample();
            userExample.createCriteria().andNameEqualTo(user.getName()).andPasswordEqualTo(user.getPassword());
            List <User> users = userMapper.selectByExample(userExample);
            if(users.isEmpty()){
                model.addAttribute("error", "用户名或密码错误");
                return "login";

            }else {
                User dbuser = users.get(0);
                response.addCookie(new Cookie("token", dbuser.getToken()));
                return "redirect:/";
            }

        }
        return "redirect:/";
    }

    public String account(User user, User accountUser, String newPass, String newName, Model model) {
        UserExample userExample = new UserExample();
        userExample.createCriteria().andAccountIdEqualTo(accountUser.getAccountId());
        List<User> users = userMapper.selectByExample(userExample);
        if(users.isEmpty()){
            throw new CustomizeException(ExceptionEnum.USER_ERROR);
        }
        User dbuser = users.get(0);
        //判断账户是否重复与数据库中重复，与自己相同时则不计
        if(!Objects.equals(dbuser.getName(), newName)){
            UserExample dbuserExample = new UserExample();
            dbuserExample.createCriteria().andNameEqualTo(newName);
            if(!userMapper.selectByExample(dbuserExample).isEmpty()){
                model.addAttribute("error", "该账户已被注册");
                return "user";
            }
        }
        //判断当前登录用户是否有账户密码
        if((dbuser.getPassword()==null & dbuser.getName()==null) || (dbuser.getPassword().isEmpty() & dbuser.getName().isEmpty())){
            //无账户密码直接设置
            if(!Objects.equals(user.getName(), "") & !Objects.equals(user.getPassword(), "")){
                dbuser.setName(user.getName());
                dbuser.setPassword(user.getPassword());
                dbuser.setGmtModified(System.currentTimeMillis());
                userMapper.updateByPrimaryKeySelective(dbuser);
            }else {
                model.addAttribute("error", "请填写账户密码");
            }
        }else {
            //有账户密码，判断是否正确
            if (dbuser.getPassword().equals(user.getPassword()) & dbuser.getName().equals(user.getName())) {
                //密码正确，修改信息
                if (!Objects.equals(newPass, "") | !Objects.equals(newName, "")) {
                    if (!Objects.equals(newPass, "")) {
                        dbuser.setPassword(newPass);
                    }
                    if (!Objects.equals(newName, "")) {
                        dbuser.setName(newName);
                    }
                    dbuser.setGmtModified(System.currentTimeMillis());
                    userMapper.updateByPrimaryKeySelective(dbuser);
                    model.addAttribute("success", "账号更新成功");
                }else {
                    model.addAttribute("error", "请填写你要更改的信息");
                }


            } else {
                model.addAttribute("error", "用户名或密码错误");
            }
            return "user";
        }
        return "user";
    }
}
